package priv.pic.to.link.main.util;

import com.tulskiy.keymaster.common.HotKey;
import com.tulskiy.keymaster.common.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.lang.reflect.Field;
import java.util.*;

/**
 * Created by Evan on 2018/4/27.
 */
public class ProviderUtil {

    private static Logger logger = LoggerFactory.getLogger(ProviderUtil.class);

    /**
     * hotKeys contains only KeyStroke
     *
     * @param provider
     * @param hotKeys
     */
    public static void registerHotKeys(Provider provider, List<HotKey> hotKeys) {
        for (HotKey hotKey : hotKeys) {
            provider.register(hotKey.keyStroke, hotKey.listener);
        }
        checkHotKeys(provider, hotKeys);
    }


    private static void checkHotKeys(Provider provider, List<HotKey> toRegisterHKs) {
        ArrayList<KeyStroke> successfulKS = new ArrayList<>();
        ArrayList<KeyStroke> failedKS = new ArrayList<>();
        try {
            Thread.sleep(500 * toRegisterHKs.size());
            Set<KeyStroke> registeredKS = getRegisteredKeyStrokes(provider);
            for (HotKey toRegisterHK : toRegisterHKs) {
                if (registeredKS.contains(toRegisterHK.keyStroke)) {
                    successfulKS.add(toRegisterHK.keyStroke);
                } else {
                    failedKS.add(toRegisterHK.keyStroke);
                }
            }
        } catch (Exception e) {
            logger.error("快捷键检测异常，程序退出!", e);
        }
        if (successfulKS.size() != toRegisterHKs.size()) {
            TipUtil.warn("有快捷键注册失败，程序退出：" + failedKS);
            System.exit(0);
        }
    }

    public static Map<Integer, HotKey> getHotKeys(Provider provider) throws NoSuchFieldException, IllegalAccessException {
        Class<? extends Provider> providerClass = provider.getClass();
        Field hotKeys = providerClass.getDeclaredField("hotKeys");
        hotKeys.setAccessible(true);
        return (Map<Integer, HotKey>) hotKeys.get(provider);
    }

    public static Set<KeyStroke> getRegisteredKeyStrokes(Provider provider) throws NoSuchFieldException, IllegalAccessException {
        Map<Integer, HotKey> hotKeys = getHotKeys(provider);
        HashSet<KeyStroke> keyStrokes = new HashSet<>();
        for (HotKey hotKey : hotKeys.values()) {
            keyStrokes.add(hotKey.keyStroke);
        }
        return keyStrokes;
    }
}
